<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <input type="button" value="查看用户详情" @click="loadData">
  <div v-if="user">
    <h1>用户详情</h1>
    <div>
      <p>id: {{user.id}}</p>
      <p>姓名: {{user.name}}</p>
      <p>年龄: {{user.age}}</p>
      <p>邮箱: {{user.email}}</p>
      <!--使用过滤器来格式化日期-->
      <p>出生日期: {{user.birthday|formatDate(3)}}</p>
    </div>
  </div>
  <h1 v-else>暂无用户信息</h1>
</div>


<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
  var vm = new Vue({
    el: '#app',

    data: {
      user: null
    },

    methods: {
      loadData: function () {
        var that =this;
        var url = "http://localhost:63342/day03/data/user.json";
        axios
        .get(url)
        .then(function (res) {
          // 把响应的用户信息赋值给 user
          that.user = res.data;
        })
        .catch(function (err) {
          console.log(err)
        })
      }
    },

    // 定义过滤器
    filters:{
      /**
       * 对日期进行格式化
       * @param milliseconds 日期的毫秒数
       * @param formatType 1 表示年月日，2 表示时分秒 3 表示年月日时分秒
       * @returns {string}
       */
      formatDate:function(milliseconds,formatType){
        console.log(milliseconds)
        var date = new Date(milliseconds);
        var fullYear = date.getFullYear();
        var month = date.getMonth()+1;
        if(month <10){
          month ="0" + month;
        }
        var date1 = date.getDate();
        if(date1 <10){
          date1 ="0" + date1;
        }

        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();

        if(formatType===1){
          return `${fullYear}-${month}-${date1}`;
        }else if(formatType ===2){
          return `${hours}:${minutes}:${seconds}`;
        }else if(formatType ===3){
          return `${fullYear}-${month}-${date1} ${hours}:${minutes}:${seconds}`;
        }else{
          return `${fullYear}-${month}-${date1}`;
        }

      }
    }
  });
</script>
</body>
</html>
